package com.LeeCode;

import org.junit.jupiter.api.Test;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 字母异位词分组
 * **/

public class Code049 {
    public static void main(String[] args) {
        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        System.out.println(new Code049().groupAnagrams1(strs));
    }

    public List<List<String>> groupAnagrams(String[] strs) {
        int sum = 0;
        List<List<String>> res = new ArrayList();
        HashMap<String, Integer> map = new HashMap<>();

        for (String str : strs) {
            char[] array = str.toCharArray();
            Arrays.sort(array);
            String key = new String(array);

            if (!map.containsKey(key)) { // 一个新目标
                map.put(key, sum++);
                List<String> strings = new ArrayList<>();
                strings.add(str);
                res.add(strings);
            } else {
                res.get(map.get(key)).add(str);
            }
        }
        System.out.println(sum);
        return res;
    }

    public List<List<String>> groupAnagrams1(String[] strs) {
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        for (String str : strs) {
            char[] array = str.toCharArray();
            Arrays.sort(array);
            String key = new String(array);
            List<String> list = map.getOrDefault(key, new ArrayList<String>());
            list.add(str);
            map.put(key, list);
        }
        return new ArrayList<List<String>>(map.values());
    }


    @Test
    public void test() {
        String str = "bdcaeaa";
        String sortedStr = str.chars() // 将字符串转换为 IntStream
                .sorted() // 排序
                .mapToObj(c -> String.valueOf((char) c)) // 转回字符
                .collect(Collectors.joining()); // 连接成字符串
        System.out.println(sortedStr); // 输出 "abcde"
    }
}
